// Copyright (c) Microsoft Corporation. All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Microsoft.TeamFoundation.Migration.Toolkit;
using System.Globalization;

namespace Microsoft.TeamFoundation.Migration.VersionControl.Wss
{
    public class PutDocumentResult : VermeerRpcResult
    {
        public PutDocumentResult(string rpcPacket)
            : base(rpcPacket)
        {
        }

        public int DocumentRevision
        {
            get
            {
                if (m_docRev == -1)
                {
                    return loadDocRev();
                }

                return m_docRev;
            }
        }

        private int loadDocRev()
        {
            VermeerList metaList = getMetaInfoList();

            foreach (VermeerListItem item in metaList.Items)
            {
                if (item.Name == "vti_sourcecontrolversion")
                {
                    Debug.Assert(item.Value[0] == 'V');
                    m_docRev = int.Parse(item.Value.Substring(1), CultureInfo.InvariantCulture);
                    break;
                }
            }

            if (m_docRev == -1)
            {
                throw new MigrationException("Unable to locate document revision");
            }

            return m_docRev;
        }

        private VermeerList getMetaInfoList()
        {
            if (m_metaInfoListCache == null)
            {
                foreach (VermeerParagraph p in Paragraphs)
                {
                    if (p.Name == "document")
                    {
                        foreach (VermeerList list in p.Lists)
                        {
                            if (list.Name == "document")
                            {
                                foreach (VermeerList metaList in list.Lists)
                                {
                                    if (metaList.Name == "meta_info")
                                    {
                                        m_metaInfoListCache = metaList;
                                        return m_metaInfoListCache;
                                    }
                                }
                            }
                        }
                    }
                }

                throw new MigrationException("Unable to locate meta_info list");
            }
            else
            {
                return m_metaInfoListCache;
            }
        }

        VermeerList m_metaInfoListCache;
        int m_docRev = -1;
    }
}
